﻿
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Teigha.DatabaseServices;
using SRB.Tg.Model;
using Teigha.Runtime;
using SRB.Tg.DrawingStandard;
using SRB.Tg.Cad_Bll;
using Teigha.Export_Import;
using System.Drawing;
using Teigha.Geometry;
using Teigha.GraphicsSystem;
using SRB.Tg.Cad_Bll;
using System.Collections.Specialized;
using System.IO;
using SRB.Tg.Operate;
using SRB.Tg.Common;
using SRB.Tg.Operate.Operate;
using System.Data;

namespace ExportBlankDrawing
{
    public class ExportBlankDrawing
    {
        static string appPath = AppDomain.CurrentDomain.SetupInformation.ApplicationBase + "CADFiles";
        static System.Data.DataTable dtQuantity;
        static System.Data.DataTable dtProjectConfig;
        static System.Data.DataTable dtCategory;

        public static string DrawingBlankDrawing(string bridgeId, string categoryId, string _appPath = "")
        {
            string filePath = "";

            string sqlDrawing = "select * from busi_bridge_catalog where  (bridge_main_id='" + bridgeId + "' || bridge_id='" + bridgeId + "' ) and id='" + categoryId + "'";
            dtCategory = MySqlHelper.ExecuteDataTable(sqlDrawing, CommandType.Text);
            string sqlBridgeConfig = "select * from busi_project_config where bridge_id='" + bridgeId + "'";
            dtProjectConfig = MySqlHelper.ExecuteDataTable(sqlBridgeConfig, CommandType.Text);
            PictureFrameTools.GetBridgeConfig(dtProjectConfig);
            string file = "";
            List<string> fileList = new List<string>();
            if (!string.IsNullOrWhiteSpace(_appPath))
                appPath = _appPath;
            if (dtCategory.Rows.Count > 0)
            {
                DrawingConfigModel drawingConfigModel = new DrawingConfigModel();
                using (Services svc = new Services())
                {
                    SystemObjects.DynamicLinker.LoadApp("GripPoints", false, false);
                    SystemObjects.DynamicLinker.LoadApp("PlotSettingsValidator", false, false);

                    HostApplicationServices.Current = new HostAppServ(svc);
                    Environment.SetEnvironmentVariable("DDPLOTSTYLEPATHS", ((HostAppServ)HostApplicationServices.Current).FindConfigPath(String.Format("PrinterStyleSheetDir")));
                    using (Database db = new Database())
                    {
                        HostApplicationServices.WorkingDatabase = db;

                        InitConfig.InitStandardConfig(db, bridgeId);
                        drawingConfigModel = PictureFrameTools.GetDrawingConfig(dtCategory, categoryId, dtProjectConfig);
                        #region 模型空间到布局空间投影处理

                        LayoutTools.CreateBlankLayout(db, "图纸",  Extensions.leftWidth, Extensions.rightWidth, Extensions.bottomHeight, Extensions.topHeight, 1, int.Parse(dtCategory.Rows[0]["pages"].ToString()));
                        Point2d tKPoint = Point2d.Origin;

                        Extents2d ex = new Extents2d();
                        PictureFrameTools.AddPaperDBText(db, tKPoint, drawingConfigModel, ref ex, int.Parse(dtCategory.Rows[0]["pages"].ToString()));

                        #endregion
                 

                        if (db != null)
                        {
                            creatFolder(appPath + "\\BlankDrawing");
                            //file = appPath + "\\AviationBridgeGA\\桥型图.dwg";
                            file = appPath + "\\BlankDrawing\\" + drawingConfigModel.drawing_no + " " + drawingConfigModel.name + ".dwg";
                            db.SaveAs(file, DwgVersion.vAC18);

                        }
                    }
                }
                using (Services ser = new Services())
                {
                    SystemObjects.DynamicLinker.LoadApp("GripPoints", false, false);
                    SystemObjects.DynamicLinker.LoadApp("PlotSettingsValidator", false, false);

                    HostApplicationServices.Current = new HostAppServ(ser);
                    Environment.SetEnvironmentVariable("DDPLOTSTYLEPATHS", ((HostAppServ)HostApplicationServices.Current).FindConfigPath(String.Format("PrinterStyleSheetDir")));
                    //打开数据库(dwg⽂件)
                    using (Database database = new Database(false, false))//不加参数会出错
                    {

                        database.ReadDwgFile(file, FileOpenMode.OpenForReadAndAllShare, false, "");
                        LayoutTools.PlotDrawingByTK(database, "图纸", "ISO_full_bleed_A3_(420.00_x_297.00_MM)", "monochrome.ctb", "DWG To PDF.pc3", file, out filePath, ref fileList);
                    }
                }

                #region 合并pdf   
                FileInfo filepath = new FileInfo(file);
                string dir = filepath.DirectoryName + "\\PDF\\";
                string fileName = drawingConfigModel.drawing_no + " " + drawingConfigModel.name;
                filePath = dir + fileName + ".pdf";
                ITextPdfHelper.mergePDFFiles(fileList, filePath);
                #endregion

                if (!File.Exists(filePath))
                    filePath = file.Replace(".dwg", "") + ".dwg";

                return filePath;
            }
            return null;
        }

  
        public static void creatFolder(String path)
        {
            //不存在 则创建
            if (!Directory.Exists(path))
            {
                Directory.CreateDirectory(path);
            }
        }
    }
}
